package com.stottlerhenke.simbionic.editor.parser;

import java.util.ArrayList;

import com.stottlerhenke.simbionic.api.SB_VarType;


public class SB_FunctionNode extends SB_ParseNode {
  private String _name;
  private ArrayList _args = new ArrayList() ;

  public SB_FunctionNode(String funcName,SB_VarType returnType) {
    super(returnType);
    _name = funcName;
  }
  /**
   * @return the name of the function
   */
  public String GetFunction() { return _name; }

  /**
   * @return the number of arguments to the function
   */
  public int GetNumArgs() { return _args.size(); }

  /**
   * 
   * @return a list of SB_ParseNode objects that represent the arguments
   */
  public ArrayList GetArgs() {return _args; }
  
  /**
   * @param index the index of the argument to return
   * @return the index-th argument of the function
   */
  public SB_ParseNode GetArg(int index) { return (SB_ParseNode)_args.get(index); }

  public SB_ErrorNode GetNextError(SB_ErrorNode lastError) {
    SB_ErrorNode err = null;
    SB_ParseNode it;
    for(int i = 0; i <_args.size(); i++){
      it = (SB_ParseNode)_args.get(i);
      err = it.GetNextError(lastError);
      if(err != null)
        break;
    }
    return err;
  }
  public boolean IsValid(){
    SB_ParseNode it;
    // check arguments
    for (int i= 0; i < _args.size(); i++)
    {
      it = (SB_ParseNode)_args.get(i);
      if (!it.IsValid())
      {
        return false;
      }
    }
    return true;
  }
  public void AddArgument(SB_ParseNode arg){
        _args.add(arg);
  }
  public void ReplaceArg(int index, SB_ParseNode arg){
	  _args.set(index, arg);
  }
  public boolean ContainsVariable(String varName) {
    // check arguments
    SB_ParseNode it;
    for (int i=0; i < _args.size(); i++)
    {
       it = (SB_ParseNode)_args.get(i);
       if (it.ContainsVariable(varName))
       {
          return true;
        }
    }
    return false;

  }
  public boolean ContainsFunction(String funcName) {
    if (_name == funcName) return true;
    SB_ParseNode it;
    // do any of the arguments contain the function?
    for (int i = 0; i < _args.size(); i++)
    {
      it = (SB_ParseNode)_args.get(i);
      if (it.ContainsFunction(funcName))
      {
        return true;
      }
    }
    return false;
  }
  public String ToString() {
    String str = new String (_name);
    str += "(";
    SB_ParseNode it;

    for (int i = 0; i < _args.size(); i++)
    {
      it = (SB_ParseNode)_args.get(i);
      str += it.ToString();

      if (i != _args.size()-1)
        str += ",";
     }
      return str + ")";
  }

}